package com.study.connect.handler;

import com.study.connect.message.InvokeResultDTO;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

/**
 * 客户端请求对象编码
 */
@Slf4j
public class InvokeResultToByteEncoderHandler extends MessageToByteEncoder<InvokeResultDTO> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, InvokeResultDTO invokeResultDTO, ByteBuf out) throws Exception {
        ByteBuf buffer = channelHandlerContext.alloc().buffer();
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);) {
            objectOutputStream.writeObject(invokeResultDTO);
            objectOutputStream.flush();
            buffer.writeBytes(byteArrayOutputStream.toByteArray());
        } catch (Exception e) {
            log.error("对象转换byte流异常：{}", e);
        } finally {
            out.writeBytes(buffer);
        }
    }
}